﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace SwaggerSdk;
public class HttpClientService
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;
    private readonly string _baseUrl;
    private readonly string _token;
    private readonly string _contentType;

    public HttpClientService(HttpClient httpClient, IConfiguration configuration)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _baseUrl = _configuration["Settings:BaseUrl"]??"";
        _token = _configuration["Settings:Token"];
        _contentType = _configuration["Settings:ContentType"];

        // 设置 HttpClient 的基础地址
        _httpClient.BaseAddress = new Uri(_baseUrl);
    }

    // 发送 GET 请求
    public async Task<T> GetAsync<T>(string endpoint, Dictionary<string, string> queryParams = null)
    {
        try
        {
           
            Console.WriteLine("22222222222");
            var response = await SendRequestAsync(endpoint, HttpMethod.Get, queryParams: queryParams);
            Console.WriteLine(response);
            return await HandleResponse<T>(response);
        }
        catch (Exception ex)
        {

            throw;
        }

    }

    public async Task<HttpResponseMessage> SendRequestAsync(string endpoint, HttpMethod method, string content = null, Dictionary<string, string> queryParams = null)
    {
        // 构建完整的 URL
        var url = BuildUrlWithParams(endpoint, queryParams);

        // 创建请求消息
        var requestMessage = new HttpRequestMessage(method, url);

        // 设置请求头
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
        requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(_contentType));

        // 如果有内容，设置请求体
        if (!string.IsNullOrEmpty(content))
        {
            requestMessage.Content = new StringContent(content, Encoding.UTF8, _contentType);
        }

        // 发送请求
        return await _httpClient.SendAsync(requestMessage);
    }
    // 处理响应并返回模型
    private async Task<T> HandleResponse<T>(HttpResponseMessage response)
    {
        if (response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<T>(responseBody);
        }
        else
        {
            // 错误处理：你可以抛出自定义异常或返回默认值
            throw new HttpRequestException($"Request failed with status code {response.StatusCode}");
        }
    }
    private string BuildUrlWithParams(string endpoint, Dictionary<string, string> queryParams)
    {
        if (queryParams == null || queryParams.Count == 0)
            return endpoint;

        var queryString = string.Join("&", queryParams.Select(kv => $"{kv.Key}={kv.Value}"));
        return $"{endpoint}?{queryString}";
    }
}
